/**
    @author: administrator
    @date:   2020/12/8
    @note:
**/
package impl

import (
	"math/rand"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

//用户信息
type UserInfo struct {
	Uid string `json:"uid"`	//用户id
	Nickname string `json:"nickname"`	//用户昵称
	Image string `json:"image"`	//用户头像
	RoomID int64 `json:"roomid"` //房间id
	LoginTime string `json:"login_time"` //登陆的时间
	Ip string `json:"ip"`
}

//使用连接 创建一个用户
func (u UserInfo) CreateUserInfo(query url.Values,ip string) (Info UserInfo){
	uid := query.Get("uid")
	img:=query.Get("img")
	if img==""{
		img ="http://127.0.0.1:7777/img/a1.jpg"
	}
	t:=time.Now().Unix() //现行时间戳
	return UserInfo{
		Uid:uid,
		Nickname:getRandNickName(),
		Image:img,
		RoomID:1,
		LoginTime:time.Unix(t,0).Format("2006-01-02 15:04:05"),
		Ip:ip,
	}
}


//返回随机的昵称
func getRandNickName() string{
	var prefixList = [...]string{"呆呆的","可爱的","酷酷的","美美的","残暴的","无敌的","猥琐的","搞笑的","自恋的","潇洒的","帅帅的","标致的","温顺的","体贴的","臭美的","美味的","可口的","好吃的"}
	var nameList = [...]string{"兔子","土豆","西瓜","猫咪","狗子","番茄","橘子","西瓜刀","计算器","抱枕","熊猫","小猪","佩琪","千里马","眼泪","帽子","手机","电脑","桌子","椅子","盆栽","喷子","油烟机","冰箱","电视机","客厅","浴室","餐厅","西餐","太阳","向日葵","西兰花","意大利面"}
	return prefixList[rand.Intn(len(prefixList)-1)] + nameList[rand.Intn(len(nameList)-1)]
}

//获取ip
func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

//获取客户端ip
func ClientPublicIP(r *http.Request) string {
	var ip string
	for _, ip = range strings.Split(r.Header.Get("X-Forwarded-For"), ",") {
		ip = strings.TrimSpace(ip)
		if ip != "" {
			return ip
		}
	}

	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != ""  {
		return ip
	}

	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
			return ip
	}

	return ""
}


